package com.ht.db.router.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.ht.db.router.core.DynamicDatasource;
import com.ht.db.router.aop.DynamicMybatisPlugin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@ComponentScan(basePackages = "com.ht.*")
public class DBRouterAutoConfiguration {

    /**
     * 初始化加载动态数据源
     */
    @Bean
    public DataSource dataSource(DBRouterProperties dbRouterProperties) {
        Map<Object, Object> targetDataSources = dbRouterProperties.getDatabases().entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, HashMap::new));
        DynamicDatasource dynamicDatasource = new DynamicDatasource();
        dynamicDatasource.setTargetDataSources(targetDataSources);
        DruidDataSource defaultDB = dbRouterProperties.getDatabases().get(dbRouterProperties.getDefaultDB());
        dynamicDatasource.setDefaultTargetDataSource(defaultDB);
        return dynamicDatasource;
    }

    @Bean
    public DynamicMybatisPlugin dynamicMybatisPlugin() {
        return new DynamicMybatisPlugin();
    }

}
